package mvc.controller;

import java.util.Optional;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import bean.entity.User;
import jakarta.servlet.http.HttpSession;
import service.UserService;
import spring.SpringContextUtil;
import utils.MDGenerator;

// RestController对返回值进行了处理，无法返回视图
@Controller
public class UserController{
  /**
   * 
   * 普通的登录页面请求，判断当前是否登录，若已登录则返回message视图，否则返回login视图。
   * 
   * */
  @GetMapping("/login")
  public String load(HttpSession session) {
    if(session.getAttribute("uid") != null) {
      return "redirect:message";
    }else {
      return "login";
    }
  }
  
  @PostMapping("/loginsubmit")
  public String submit(@RequestParam("name") String name, @RequestParam("password") String password, HttpSession session) {
    UserService us = (UserService) SpringContextUtil.getBean("userService");
    Optional<String> uid = us.validate(name, MDGenerator.md5(password));
    if(uid.isPresent()) {
      session.setAttribute("name", name);
      session.setAttribute("uid", uid.get());
      return "redirect:message";
    }else {
      return "login";
    }
  }
  
  @GetMapping("/register")
  public String load() {
    return "register";
  }
  
  @PostMapping("/registersubmit")
  public String submit(@ModelAttribute("userInfo") User user) {
    UserService us = (UserService) SpringContextUtil.getBean("userService");

    // 基于POST参数创建用户对象
    user.setUid(user.getName().charAt(0) + String.valueOf(System.currentTimeMillis()));
    user.setPassword(MDGenerator.md5(user.getPassword()));
    // 注册，并根据注册结果进行响应
    if(us.register(user).isPresent()) {
      return "redirect:login";
    }else {
      return "register";
    }
  }
  
  @GetMapping("/logout")
  public String logout(HttpSession session) {
    //session.removeAttribute("uid");
    //session.removeAttribute("name");
    session.invalidate();
    return "redirect:message";
  }

}
